﻿package src.game {
	import src.tools.FpsCounter;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class Game extends Sprite {
		private var stageWidth:int;
		private var stageHeight:int;
		private var counter:FpsCounter;
		private var background:Sprite;
		private var frameRate:TextField;
		private var level:Level;
		private var loop:Boolean = false;
		
		public function Game(w:int, h:int) {
			stageWidth = w;
			stageHeight = h;
			//creating backgroudn
			background = new Sprite();
			background.graphics.beginFill(0xffcc00);
			background.graphics.drawRect(0,0,w,h);
			this.addChild(background);
			//creating fps counter
			frameRate = new TextField();
			this.addChild(frameRate);
			//creating level
			createLevel(null);
			counter = new FpsCounter();
			//starting gameloop
			this.addEventListener(Event.ENTER_FRAME, gameLoop);
			this.addEventListener(MouseEvent.CLICK, mouseClick);
		}
		
		private function gameLoop(event:Event):void {
			//calculating fps
			counter.tick();
			frameRate.textColor = 0xffffff;
			frameRate.text = "FPS "+String(counter.getFps());
			if (loop) {
			//moving paddles
				level.moveBall();
				level.checkCollisions();
				level.checkForNextLevel();
			}
			level.movePaddle(this.mouseX, this.mouseY);
			//loop = false;
		}
		
		private function mouseClick(event:MouseEvent):void {
			loop = true;
		}
		
		private function createLevel(event:GameEvent):void {
			trace("creating level");
			var id:int;
			var ballPosition:Point;
			var ballMovement:Point;
			var ballSpeed:Number = 0;
			
			//getting the level map
			var levelMap:LevelMap = new LevelMap(stageWidth, stageHeight, 32);
			if (event == null) {
				id = 1;
				ballPosition = levelMap.getStartingBallPostition();
				ballMovement = levelMap.getStartingBallDirection();
			}
			else {
				id = level.getNextLevelId();
				ballPosition = level.getBallNewPosition();
				ballMovement = level.getBallDirection();
				level.removeEventListener(GameEvent.LEVEL_CLEARED, createLevel);
				this.removeChild(level);
			}

			//creating new level
			level = null;
			level = new Level(levelMap.getLevelAt(id));
			
			//neighbour levels
			var next:Array = levelMap.getNextLevelsIds(id);
			level.setNextLevelIds(next[0], next[1], next[2], next[3]);
			level.addEventListener(GameEvent.LEVEL_CLEARED, createLevel);
			
			//creating paddles
			var paddles:Array = levelMap.getPaddlesAt(id);
			for (var i:int = 0; i<paddles.length; i++)
				level.setPaddle(paddles[i][0], paddles[i][1], paddles[i][2]);
				
			//initating ball
			(ballSpeed == 0) ? level.initBall(ballPosition, ballMovement) : level.initBall(ballPosition, ballMovement, ballSpeed);
			this.addChild(level);
			this.setChildIndex(frameRate, this.numChildren-1);
		}
	}
}